import {Component, ViewChild, SimpleChanges, Input, SimpleChange, Output, EventEmitter} from '@angular/core';
import {Router} from "@angular/router";
import {PromptService} from "../prompt/prompt.service";
import {CommonService} from "../common.service";
import {FileUploader, ParsedResponseHeaders, FileItem} from "ng2-file-upload";
import {UploadFileResult} from "../../models/uploadFileResult";
import {LoadingService} from "../loading/loading.service";


declare var $: any;
@Component({
    moduleId: module.id,
    selector: 'upload-component',
    templateUrl: "./upload.html"
})


export class UploadComponent {

    uploader: FileUploader;
    uploadFileResult: UploadFileResult = new UploadFileResult();
    @Output() getResult = new EventEmitter<UploadFileResult>();
    @ViewChild("uploadBtn") uploadBtn: any
    private type: string

    constructor(private loadingService: LoadingService, private  promptService: PromptService, private  commonService: CommonService, private router: Router,) {
        this.uploader = new FileUploader(
            {
                url: this.commonService.getRequestProUrl() + "/api/file/upload_file",
                allowedFileType: ["xls", "xlsx"],
                method: "POST",
                autoUpload: true
            }
        )


        this.uploader.onSuccessItem = (item: FileItem, response: any, status: number, headers: ParsedResponseHeaders)=> {
            let result: any = JSON.parse(response)
            if (result.success) {
                this.promptService.info("上传成功")
                let back: UploadFileResult = new UploadFileResult()
                back.name = item._file.name
                if (this.type == 'productPriceDisplay') {
                    back.fileKey = result.result
                } else {
                    back.url = result.result
                }
                this.getResult.emit(back)
            } else {
                this.promptService.warning(result.error.message);
            }
        }

        this.uploader.onCompleteItem = (item: FileItem)=> {
            this.loadingService.end();
        }

        this.uploader.onBeforeUploadItem = (item: FileItem)=> {
            this.loadingService.start();
        }


        this.uploader.onWhenAddingFileFailed = (item: any, filter: any, options: any): any=> {
            if (filter.name == "fileType") {
                this.promptService.warning("请上传excel格式文件,其他格式暂时不支持")
            }
        }

        this.uploader.onBuildItemForm = (fileItem, form)=> {
            form.append('type', this.type);
        };
    }


    upload(type: string) {
        this.type = type;
        $(this.uploadBtn.nativeElement).trigger("click")
    }
}